// Store schedule data
let scheduleData = {};
let currentCell = null;

// Generate random pastel color
function getRandomPastelColor() {
    const hue = Math.floor(Math.random() * 360);
    return `hsl(${hue}, 70%, 90%)`;
}

// Get the first day of current month
function getFirstDayOfMonth() {
    const today = new Date();
    return new Date(today.getFullYear(), today.getMonth(), 1);
}

// Calculate week number within the month
function getWeekOfMonth(date) {
    const firstDay = getFirstDayOfMonth();
    const dayDiff = Math.floor((date - firstDay) / (24 * 60 * 60 * 1000));
    return Math.ceil((dayDiff + firstDay.getDay() + 1) / 7);
}

// Update dates based on selected week
function updateDates(weekNum) {
    const firstDay = getFirstDayOfMonth();
    const startDate = new Date(firstDay);
    startDate.setDate(firstDay.getDate() + (weekNum - 1) * 7 - firstDay.getDay());

    const headers = document.querySelectorAll('.grid-header .date');
    headers.forEach((dateDiv, index) => {
        if (dateDiv) {
            const date = new Date(startDate);
            date.setDate(date.getDate() + index);
            dateDiv.textContent = `${date.getMonth() + 1}-${date.getDate()}`;
        }
    });

    // Update schedule display
    updateScheduleDisplay(weekNum);
}

function updateScheduleDisplay(weekNum) {
    const cells = document.querySelectorAll('.grid-cell');
    cells.forEach(cell => {
        const key = `${weekNum}-${cell.dataset.shift}-${Array.from(cell.parentNode.children).indexOf(cell)}`;
        const data = scheduleData[key];

        if (data) {
            cell.innerHTML = `
                        <div class="service-name">${data.service}</div>
                        <div class="employee-name">${data.name}</div>
                    `;
            cell.style.backgroundColor = data.color;
        } else {
            cell.innerHTML = '';
            cell.style.backgroundColor = '';
        }
    });
}

function highlightToday() {
    const today = new Date();
    const dayOfWeek = today.getDay();

    document.querySelectorAll('.grid-header').forEach(header => {
        header.classList.remove('today');
    });

    const headerToHighlight = document.querySelector(`.grid-header[data-day="${dayOfWeek}"]`);
    if (headerToHighlight) {
        headerToHighlight.classList.add('today');
    }
}

function toggleDropdown() {
    const dropdown = document.querySelector('.week-dropdown');
    const arrow = document.querySelector('.dropdown-arrow');
    dropdown.classList.toggle('show');
    arrow.classList.toggle('active');
}

function selectWeek(week) {
    document.querySelector('.week-title').textContent = `第${week}周`;
    updateDates(week);
    toggleDropdown();
}

function openModal(cell) {
    currentCell = cell;
    document.getElementById('shiftModal').style.display = 'block';
}

function closeModal() {
    document.getElementById('shiftModal').style.display = 'none';
    document.getElementById('shiftForm').reset();
    currentCell = null;
}

function submitForm(event) {
    event.preventDefault();

    if (currentCell) {
        const weekNum = parseInt(document.querySelector('.week-title').textContent.match(/\d+/)[0]);
        const key = `${weekNum}-${currentCell.dataset.shift}-${Array.from(currentCell.parentNode.children).indexOf(currentCell)}`;

        const data = {
            service: document.getElementById('service').value,
            name: document.getElementById('name').value,
            employeeId: document.getElementById('employeeId').value,
            notes: document.getElementById('notes').value,
            color: getRandomPastelColor()
        };

        scheduleData[key] = data;

        currentCell.innerHTML = `
                    <div class="service-name">${data.service}</div>
                    <div class="employee-name">${data.name}</div>
                `;
        currentCell.style.backgroundColor = data.color;
    }

    closeModal();
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date();
    const currentWeek = getWeekOfMonth(today);
    selectWeek(currentWeek);
    highlightToday();
});

// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    const dropdown = document.querySelector('.week-dropdown');
    const selector = document.querySelector('.week-selector');
    if (!selector.contains(event.target) && dropdown.classList.contains('show')) {
        dropdown.classList.remove('show');
        document.querySelector('.dropdown-arrow').classList.remove('active');
    }
});

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('shiftModal');
    if (event.target === modal) {
        closeModal();
    }
};